<template>
  <div id="downloadCenterCampus" class="container">
    <div class="content">
      <!-- <div class="title">全部资源</div> -->
      <div class="panel">
        <div class="condition">
          <div class="row_one">
            <el-cascader
              v-model="tabledisplayObj.parentId"
              style="width:12%;float: left;margin-left:.1rem; "
              :props="props"
              clearable
              :show-all-levels="false"
              placeholder="请选择目录"
            ></el-cascader>
            <el-select
              style="width:12%;float: left;margin-left:.1rem; "
              v-model="isDownload"
              clearable
              placeholder="请选择下载状态"
            >
              <el-option
                v-for="item in statusList"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              ></el-option>
            </el-select>
            <el-input
              v-model="tabledisplayObj.name"
              style="width:12%;float: left;margin-left:.1rem;"
              placeholder="输入资源文件名称"
              class="input_search"
              clearable
            ></el-input>
            <div class="search_btn" style="margin-left:0.1rem;" @click="searchObj">搜索</div>
            <div class="btn_user_defined" style="margin-left:0.1rem;" @click="cancle">重置</div>
            <!--  -->
          </div>
        </div>

        <div>
          <table class="table" cellspacing="0" style="table-layout:fixed;">
            <thead class="thead">
              <tr>
                <td style="width: 4rem;">资源名称</td>
                <td style="width: 4rem;">所属目录</td>
                <td style="width: 4rem;">上传时间</td>
                <td style="width: 4rem;">下载状态</td>
                <td style="width: 2rem;">操作</td>
              </tr>
            </thead>
            <tbody class="tbody">
              <col style="width:10%" />
              <tr v-for="item,index in resourceList">
                <td style="text-align: left;padding-left:0.5rem;">
                  <div style="display: flex;justify-content: left;align-items: left;">
                    <!-- <div class="circle"></div> -->
                    <el-checkbox
                      v-if="item.fileType != '.zip'"
                      v-model="item.isCheck"
                      :disabled="item.isDownloadable == '0'"
                      @change="boxChange(item)"
                    ></el-checkbox>
                    <div style="cursor: pointer;" @click="clickItem(item)">{{item.name}}</div>
                  </div>
                </td>
                <td
                  style="line-height: 0.52rem;display: -webkit-box;-webkit-box-orient: vertical;-webkit-line-clamp: 1;overflow: hidden;"
                >
                  <div :title="item.pathName">{{item.pathName}}</div>
                </td>
                <td>{{item.createTime}}</td>
                <td v-if="item.hasDown == 0 && item.downloadProgress == 0">未下载</td>
                <td v-else-if="item.downloadProgress != 0 && item.downloadProgress != 100">
                  <el-progress
                    :text-inside="true"
                    :stroke-width="20"
                    :percentage="item.downloadProgress"
                    :color="item.dowmloadStatus"
                  ></el-progress>
                </td>
                <td v-else-if="item.hasDown == 1 || item.downloadProgress == 100">下载完成</td>
                <td>
                  <div class="edit_btn">
                    <div
                      class="btn_img_down"
                      :class="{disable:item.isDownloadable == '0'}"
                      @click="resourceDowm(index,item)"
                    ></div>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <div class="allCheckClass">
          <el-checkbox
            @change="boxAllChange"
            v-model="isAllCheck"
            style="float: left;margin-top:0.1rem;font-size:0.16rem;margin-left:0.2rem;"
          >全选</el-checkbox>
          <div class="download_btn" @click="downloadFileList()">下载文件</div>
        </div>
        <el-pagination
          class="page"
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="tabledisplayObj.currentPage"
          @size-change="pageSizeChange"
          @current-change="tabledisplayChangePage"
          :total="tabledisplayObj.total"
        ></el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
let vm;
let user;
export default {
  data() {
    return {
      isAllCheck: false, //是否全部选中
      props: {
        //文件目录筛选，通过懒加载时间动态加载数据，设置父子不强制关联实现选中某个文件夹下的id
        lazy: true,
        checkStrictly: true,
        lazyLoad(node, resolve) {
          let user = tool.getItem(lsKey.user, true); //得到当前用户信息
          let paras = {
            parentId:
              node.value == null || node.value == undefined ? 0 : node.value,
            objectId: user.orgId
          };
          api.folderList(paras).then(function(result) {
            var data = result.data;
            let datalist = [];
            data.list.forEach(item => {
              let param = {
                value: item.id,
                label: item.name,
                leaf: false
              };
              datalist.push(param);
            });
            resolve(datalist);
          });
        }
      },
      resourceList: [],
      isDownload:null,
      statusList: [
        {
          name: "下载完成",
          value: 1
        },
        {
          name: "未下载",
          value: 0
        }
      ],
      selectDownloadList: [], //选中的下载文件列表
      tabledisplayObj: {
        currPage: 1,
        pageSize: 10,
        objectId: "",
        objectIdList: [this.$store.state.campusId],
        name: "",
        parentId: "",
        type: 2,
        userId: "",
        total: 0
      }
    };
  },
  components: {},
  methods: {
    init() {
      // vm = this;
      user = tool.getItem(lsKey.user, true); //得到当前用户信息
      let dicdata = tool.getItem(lsKey.dict, true);
      vm.tabledisplayObj.userId = user.userId;
      vm.getData();
    },
    /**搜索 */
    searchObj() {
      vm.tabledisplayObj.currPage = 1;
      vm.tabledisplayObj.parentId =
        vm.tabledisplayObj.parentId == undefined
          ? ""
          : vm.tabledisplayObj.parentId;
      console.log(vm.tabledisplayObj.parentId);
      if (
        vm.tabledisplayObj.parentId != "" ||
        vm.tabledisplayObj.parentId.length == 0
      ) {
        vm.tabledisplayObj.parentId =
          vm.tabledisplayObj.parentId[vm.tabledisplayObj.parentId.length - 1];
      } else {
        vm.tabledisplayObj.parentId = "";
      }
      vm.getData();
    },
    /**重置 */
    cancle() {
      vm.tabledisplayObj = {
        currPage: 1,
        pageSize: 10,
        objectIdList: [this.$store.state.campusId],
        name: "",
        parentId: "",
        type: 2,
        total: 0
      };
      vm.getData();
    },
    /**获取数据 */
    getData() {
      vm.tabledisplayObj.objectId = user.orgId;
      let param={
        orgId:user.orgId,
        currPage:vm.tabledisplayObj.currPage,
        pageSize:vm.tabledisplayObj.pageSize,
        campusId:vm.$store.state.campusId,
        parentId:vm.tabledisplayObj.parentId,
        isDownload:vm.isDownload,
        name:vm.tabledisplayObj.name
      }
      api.allSubfileFolderPage(param).then(function(result) {
        var data = result.data;
        if (data.resultCode == 2000) {
          data.list.forEach(item => {
            let len = item.name.lastIndexOf(".");
            item.fileType = item.name.substring(len); //文件类型
            item.downloadProgress = 0; //文件下载进度
            item.req = null; //文件下载请求
            item.downLoadPath = null; //文件下载路径
            item.dowmloadStatus = "#409EFF"; //文件下载状态
            item.isCheck = false; //文件是否被选中
          });
          vm.resourceList = data.list;
          vm.tabledisplayObj.total = data.totalCount;
        } else {
          vm.$message({
            message: data.message,
            type: "warning"
          });
          return;
        }
      });
    },
    /**下载文件 */
    downloadFileList() {
      if (vm.selectDownloadList.length == 0) {
        tool.message({
          showClose: true,
          message: "请选择文件！",
          type: "warning"
        });
        return;
      }
      let ids = [];
      //获取选中文件的下载路径
      for (let i = 0; i < vm.selectDownloadList.length; i++) {
        ids.push(vm.selectDownloadList[i].id);
      }
      api.getResourcePath({ resourceIds: ids }).then(function(result) {
        var data = result.data;
        for (let i = 0; i < data.list.length; i++) {
          for (let y = 0; y < vm.selectDownloadList.length; y++) {
            if (data.list[i].resourceId == vm.selectDownloadList[y].id) {
              vm.selectDownloadList[y].downLoadPath = data.list[i].downLoadPath;
              if (!data.list[i].success) {
                vm.$message.error(data.list[i].errorMsg);
              }
              break;
            }
          }
        }
        console.log(vm.selectDownloadList);
        for (let i = 0; i < vm.selectDownloadList.length; i++) {
          //判断当前需要下载的文件下载路径是否为空
          if (vm.selectDownloadList[i].downLoadPath != null) {
            //判断当前 需要下载的文件的是否已下载过
            if (vm.selectDownloadList[i].dowmloadStatus != "#67C23A") {
              //当次已完成下载不在下载
              vm.downloadFile(vm.selectDownloadList[i]);
            }
          } else {
            tool.message({
              showClose: true,
              message: "资源异常,暂无法下载!",
              type: "error"
            });
          }
        }
      });
    },
    /**下载文件 */
    downloadFile(item) {
      var req = new XMLHttpRequest();
      req.open("get", item.downLoadPath, true);
      //监听进度事件
      req.addEventListener(
        "progress",
        function(evt) {
          if (evt.lengthComputable) {
            var percentComplete = evt.loaded / evt.total;
            item.downloadProgress = parseInt(percentComplete * 100);
            let campusData = {};
            user.campusList.forEach(item => {
              if (item.campusId == vm.$store.state.campusId) {
                campusData = item;
              }
            });
            if (item.downloadProgress == 100) {
              //下载完成提交下载记录
              let paras = {
                resourceId: item.id,
                action: 1,
                objectId: vm.$store.state.campusId,
                objectName: campusData.name,
                createUserId: user.userId,
                createUserName: user.nickName
              };
              api.actionLogAdd(paras).then(function(data) {
                data = data.data;
                if (data.resultCode == 2000) {
                  item.dowmloadStatus = "#67C23A";
                  vm.$forceUpdate();
                } else {
                  vm.$message({
                    message: data.message,
                    type: "warning"
                  });
                }
              });
            }

            // $("#progressing").html((percentComplete * 100) + "%");
          }
        },
        false
      );
      //下载错误
      req.addEventListener(
        "error",
        function(evt) {
          item.dowmloadStatus = "#F56C6C";
          vm.$forceUpdate();
        },
        false
      );
      //下载暂停
      req.addEventListener(
        "abort",
        function(evt) {
          item.dowmloadStatus = "#E6A23C";
          vm.$forceUpdate();
        },
        false
      );
      req.responseType = "blob";
      req.onreadystatechange = function() {
        if (req.readyState === 4 && req.status === 200) {
          var filename = item.name;
          if (typeof window.chrome !== "undefined") {
            // Chrome version
            var link = document.createElement("a");
            link.href = window.URL.createObjectURL(req.response);
            link.download = filename;
            link.click();
          } else if (typeof window.navigator.msSaveBlob !== "undefined") {
            // IE version
            var blob = new Blob([req.response], {
              type: "application/force-download"
            });
            window.navigator.msSaveBlob(blob, filename);
          } else {
            // Firefox version
            var file = new File([req.response], filename, {
              type: "application/force-download"
            });
            window.open(URL.createObjectURL(file));
          }
        }
      };
      item.req = req;
      req.send();
    },
    /**
     * 点击文件
     */
    clickItem(item) {
      if (!vm.$store.state.permit["999"]) {
        tool.message({
          showClose: true,
          message: "当前用户缺少权限",
          type: "warning"
        });
        return;
      }
      var path = vm.$store.state.permit["999"].path;
      let routeData = this.$router.resolve({
        path: path,
        query: { resourceId: item.id, index: 1 }
      });
      window.open(routeData.href);
    },
    /**全选 */
    boxAllChange(val) {
      if (val) {
        vm.selectDownloadList = [];
        vm.resourceList.forEach(item => {
          if (item.isDownloadable != "0") {
            item.isCheck = true;
            vm.selectDownloadList.push(item);
          }
        });
      } else {
        vm.selectDownloadList = [];
        vm.resourceList.forEach(item => {
          item.isCheck = false;
        });
      }
    },
    boxChange(item) {
      if (item.isCheck) {
        vm.selectDownloadList.push(item);
      } else {
        vm.selectDownloadList.splice(vm.selectDownloadList.indexOf(item), 1);
      }
    },
    campusChange: function(campusId) {
      vm.tabledisplayObj.objectIdList = [campusId];
      this.getData();
    },
    pageSizeChange: function(val) {
      this.tabledisplayObj.pageSize = val;
      this.getData();
    },
    /**表格显示形式翻页 */
    tabledisplayChangePage(val) {
      this.tabledisplayObj.currPage = val;
      this.getData();
    },
    resourceDowm(index, item) {
      if (item.dowmloadStatus == "#67C23A") return;
      let ids = [item.id];
      api.getResourcePath({ resourceIds: ids }).then(function(result) {
        var data = result.data;
        item.downLoadPath = data.list[0].downLoadPath;
        if (item.downLoadPath != null) {
          vm.downloadFile(item);
        } else {
          tool.message({
            showClose: true,
            message: "资源异常,暂无法下载!",
            type: "error"
          });
        }
      });
    }
  },
  mounted() {
    vm = this;
  },
  computed: {}
};
</script>

<style lang="scss">
#downloadCenterCampus {
  .disable {
	pointer-events: none;
}
  .circle {
    width: 0.1rem;
    height: 0.1rem;
    border-radius: 50%;
    margin-right: 0.1rem;
    background-color: red;
  }
  .el-checkbox {
    margin-right: 0.1rem;
  }
  .el-checkbox__inner {
    width: 0.18rem;
    height: 0.18rem;
  }
  .el-checkbox__inner::after {
    height: 0.09rem;
    left: 0.05rem;
    position: absolute;
    top: 0.01rem;
    width: 0.04rem;
  }
  .el-input__inner {
    border-radius: 0.08rem;
    font-size: 0.16rem;
    color: #666666;
    height: 0.36rem;
    line-height: 0.36rem;
  }
  .el-input__icon {
    line-height: 0.36rem;
  }

  .input_search {
    .el-input__inner {
      background-color: rgb(247, 248, 250);
    }
  }
  .edit_btn {
    display: flex;
    justify-content: center;
    align-content: center;
    text-align: center;
    height: 0.26rem;
    line-height: 0.26rem;

    .btn_img_down {
      padding-left: 0.35rem;
      background-image: url("../../assets/img/answer_system/donwload.png");
      background-repeat: no-repeat;
      background-size: 0.2rem;
      background-position: 0.1rem center;
      cursor: pointer;
    }
  }
  .btn_user_defined {
    display: inline-block;
    width: 0.8rem;
    padding-left: 0.22rem;
    height: 0.36rem;
    line-height: 0.36rem;
    border-radius: 0.08rem;
    color: white;
    font-size: 0.16rem;
    cursor: pointer;
    letter-spacing: 0.03rem;
    background-color: #3885f8;
    position: relative;
    top: 0.01rem;
  }
  .btn_user_defined:hover {
    background-color: rgba(56, 133, 248, 0.8);
  }
}
</style>
<style scoped src="@/style/module/table.css"></style>
<style scoped src="@/style/clue_manage/clue_manage.css"></style>
<style scoped>
.right_btn {
  background-image: url(../../assets/img/clue_manage/add_white.png);
  width: 1.54rem;
}
.allCheckClass {
  position: relative;
  bottom: -0.1rem;
  left: 0;
  width: 4rem;
  overflow: hidden;
}
.download_btn {
  width: 1.76rem;
  height: 0.38rem;
  line-height: 0.38rem;
  float: left;
  margin-left: 0.1rem;
  font-size: 0.16rem;
  font-weight: bold;
  border-radius: 0.1rem;
  box-shadow: 0 0 0.2rem 0 rgba(56, 133, 248, 0.2);
  padding-left: 0.68rem;
  color: #ffffff;
  cursor: pointer;
  background-color: #259b24;
  background-repeat: no-repeat;
  background-size: 0.18rem;
  background-position: 0.38rem center;
  background-image: url(../../assets/img/clue_manage/download.png);
}

.download_btn:hover {
  background-color: rgba(37, 155, 36, 0.8);
}
</style>